from models.BaseModel import BaseModel
from peewee import *
from util.Model2Dict import m2d
from entry.Entrys import Page
class SysConfig(BaseModel):
    key = CharField(primary_key=True)
    name = CharField()
    value = CharField()
    type = CharField()
    class Meta:
        table_name = 'sys_config'
        
class SysDict(BaseModel):
    dId = BigIntegerField(column_name='d_id',primary_key=True)
    status = CharField()
    initTime = DateTimeField(column_name='init_time')
    type = CharField()
    path = CharField()
    name = CharField()
    description = CharField()
    class Meta:
        table_name = 'sys_dict'
                   
""" 字典key和value """   
class DictKeyValue(BaseModel):
    id = BigIntegerField(column_name = 'id',primary_key=True)
    dId = BigIntegerField(db_column='d_id')
    key = CharField(column_name='key')
    val = CharField()
    class Meta:
        table_name = "sys_dict_kv"

###config
""" 获取所有的配置信息 """
def getAllConfig(page:Page = None,cdn:dict = dict()):
    q =  SysConfig.select(SysConfig.key,SysConfig.value)
    if page:
        r = q.paginate(page.num,page.size).dicts()
        page.count =q.count()
        page.rows = m2d(r)
        return page.__dict__
    cType = cdn.get('type')
    if cType:
        if type(cType) == str:
            q = q.where(SysConfig.type == cType)
        elif type(cType) == list:
            q = q.where(SysConfig.type.in_(cType))
    r = q.dicts()
    return m2d(r)

""" 根据key获取某配置信息 """
def getConfigByKey(key:str):
    r = SysConfig.select(SysConfig.value).where(SysConfig.key == key,  SysConfig.type == 'user').dicts()
    if(len(r)>0):
        return m2d(r)[0]
    return None       

""" 根据key更新配置信息的属性 """
def updateConfigByKey(key:str,k):
    return SysConfig.update({'value':k}).where(SysConfig.key == key).execute() > 0

""" 添加配置信息 """
def addConfig(d:dict):
    return SysConfig.insert(d).execute() 

###dict
""" 获取所有的字典 """
def getAllDict(page:Page = Page(),condition:dict = dict()):
    query = SysDict.select()
    if(condition.get('path')):
        query = query.where(SysDict.path.startswith(condition.get('path')))
    if(condition.get('type')):
        query = query.where(SysDict.type == condition.get('type'))
    if(condition.get('name')):
        query = query.where(SysDict.name.contains(condition.get('name')))
    if(condition.get('status')):
        query = query.where(SysDict.status == condition.get('status'))
    if(condition.get('initTime')):
        start = condition.get('initTime')[0]
        end = condition.get('initTime')[1]
        query = query.where((SysDict.initTime >= start) &(SysDict.initTime <= end))
    r = query.paginate(page.num,page.size).dicts()
    page.count = query.count()
    page.rows = m2d(r)
    return page.__dict__

""" 根据path获取SysDict"""
def getDictByPathAndTYpe(path:str,type:str):
    r = SysDict.select().where(SysDict.path == path,SysDict.type == type).dicts()
    if(len(r)==0):
        return None
    return m2d(r)[0]

""" 根据did获取DictKeyValue表的kv"""
def getKvByDid(did):
    r = DictKeyValue.select(DictKeyValue.key, DictKeyValue.val).where(DictKeyValue.dId == did).dicts()
    return m2d(r)

""" 更新字典的属性 """
def updateDict(id:int,k)->bool:
    return SysDict.update(k).where(SysDict.dId == id).execute() > 0


""" 删除字典 """
def delDictById(dids:list[int]):
    return SysDict.delete().where(SysDict.dId.in_(dids)).execute()>0

""" 删除所有有did 的映射关系 """
def delDictKeyValueByDid(dids:list[int]):
    return DictKeyValue.delete().where(DictKeyValue.dId.in_(dids)).execute()

""" 添加字典 """
def addDict(d:dict):
    return SysDict.insert(d).execute() 

""" 添加字典KV """
def addDictkv(d:list[dict]):
    return DictKeyValue.insert_many(d).execute() 